class AdminController < ApplicationController
  before_filter :admin_required

  def index
    render :action=>"index", :layout=>"blank_layout"
  end

  def import_csv
    render :action=>"import_csv", :layout=>"blank_layout"
  end

  def do_import_csv
    csvdata = params['csv'].read
    name_row = Array.new
    code_row = Array.new
    converted_code_row = Array.new
    import_type = Array.new
    csvdata.each_with_index do |line,i|
#			line = line.to_utf8
			line2 = line
			line2 = line2.gsub("\r","")
			line2 = line2.gsub("\n","")
			line2 = line2.gsub('"','')
			cols = line2.split(',')
      if i==0
        name_row = cols
      elsif i==1
        code_row = cols
        converted_code_row,import_type = prepare_stock_symbol(name_row, code_row)
      else
        trade_date = Date.parse(cols[0])
        cols.each_with_index do |c,j|
          if j>0
            st = StockTrade.find(:first, :conditions=>["stock_id=? AND trade_date=?", converted_code_row[j], trade_date])
            if !st
              st = StockTrade.new
              st.stock_id = converted_code_row[j]
              st.trade_date = trade_date
            end
            if import_type[j]=='price'
              if c.empty? || c=='na'
                st.price = nil
              else
                st.price = c
                before_st = StockTrade.find(:first, :conditions=>["stock_id=? AND trade_date<?", converted_code_row[j], trade_date], :order=>"trade_date desc")
                if before_st
                  today_price = c.to_f
                  yesterday_price = before_st.price
                  if today_price
                    if yesterday_price
                      begin
                        daily_return = (today_price - yesterday_price)/yesterday_price
                        st.daily_return = daily_return
                      rescue
                      end
                    end
                  end
                end
              end
            elsif import_type[j]=='volumn'
              if c.empty? || c=='na'
                st.volumn = nil
              else
                st.volumn = c
              end
            else

            end
            st.save
          end
        end
      end
    end
    render :text=>"done", :layout=>"blank_layout"
  end

  def prepare_stock_symbol(name_row, code_row)
    converted_code_row = Array.new
    converted_code_row[0] = 0
    import_type = Array.new
    name_row.each_with_index do |n,i|
      stock_company = n
      stock_symbol = nil
      pre_symbol = code_row[i]
      if pre_symbol.include?('(V)') || pre_symbol.include?('(VO)')
        import_type[i] = 'volumn'
      else
        import_type[i] = 'price'
      end
      pre_symbol = pre_symbol.gsub('Q:','')
      if pre_symbol.include? '('
        stock_symbol = pre_symbol[0..pre_symbol.index('(')-1]
      else
        stock_symbol = pre_symbol
      end
      if i>0
        stock = Stock.find(:first, :conditions=>["intraday_symbol=?", stock_symbol])
        if !stock
          stock = Stock.find(:first, :conditions=>["s_symbol=?", stock_symbol])
          if !stock
            stock = Stock.new
            stock.s_symbol = stock_symbol
            stock.intraday_symbol = stock_symbol
            stock.detail = stock_company
            stock.save
          end
        end
        converted_code_row[i] = stock.id
      end
    end
    return converted_code_row,import_type
  end

  def backuppage
    file_dir = "#{RAILS_ROOT}/public/backupfiles/documents"
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    @file_list = Dir.entries(file_dir)
    @db_list = Dir.entries(db_dir)
    render :action=>"backuppage", :layout=>"blank_layout"
  end

  def backup
    require 'zip/zip'
    file_path = "#{RAILS_ROOT}/public/files"
    zipfile_name = "#{RAILS_ROOT}/public/backupfiles/documents/#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.zip"
    begin
      File.delete(zipfile_name)
    rescue
    end
    attachs = Attachment.find(:all, :conditions=>["a_type=? AND zip_flag=?",'I','N'])
    Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
      attachs.each do |a|
        begin
          zipfile.add(a.id.to_s, file_path + '/' + a.id.to_s)
          a.zip_flag = 'Y'
          a.save
        rescue
        end
      end
    end

    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "mysqldump -uchaiyo -p45664566 eventdb|gzip > #{db_path}/#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.sql.gz"
#    puts cmd
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def deletebackup1
    file_dir = "#{RAILS_ROOT}/public/backupfiles/documents"
    begin
      File.delete(file_dir+"/"+params[:filename])
    rescue
    end
    redirect_to :action=>"backuppage"
  end

  def deletebackup3
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    begin
      File.delete(db_dir+"/"+params[:filename])
    rescue
    end
    redirect_to :action=>"backuppage"
  end

  def restoredb
    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "gzip -d < #{db_path}/#{params[:filename]} | mysql -uchaiyo -p45664566 eventdb"
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def uploadbackup
    filename = "#{RAILS_ROOT}/public/backupfiles/databases/#{params['pfile'].original_filename.gsub(/[^a-zA-Z0-9.]/, '_')}"
    begin
      File.delete(filename)
    rescue
    end
    File.open(filename, "wb") do |f|
			f.write(params['pfile'].read)
		end
    redirect_to :action=>"backuppage"
  end
end
